<template>
<div class="schedule-table">
    <table border="1" cellpadding="0">
            <WeekTitle />
        <tr v-for="item in duration" :key="item.begin_time">
       <duration-title :title="item.title" />
        <td v-for="n in 7" :key="n"
        @click="handleTDClick(item.begin_time,n)"
        >
        <!-- {{ item.begin_time }}{{ n }} -->
      

        <schedule-card v-if="schedule[item.begin_time+'_'+n]"
        :data = "schedule[item.begin_time+'_'+n]"
        @remove-card="removeCard"
        >
       
        </schedule-card>
        </td>
        </tr>
    </table>
</div>
</template>
<script setup>
import {onMounted,reactive,toRefs,h,} from 'vue';
import './styles/index.scss';

import WeekTitle from "./WeekTitle";
import ScheduleCard from "./ScheduleCard";
import DurationTitle from "./DurationTitle";
import MyForm from "./MyForm";
import MyMessageBox from '../MyMessageBox';

import {getInitialData,updateSchedule,removeSchedule} from './apis/service.js';
import {useInitialData,useFormData} from './apis/hooks.js';
import {checkHasData} from './apis/utils.js';

const [
    data,
   setInitialData,
   setSchedule
   ] = useInitialData();

console.log(data)
const [setFormData] = useFormData();
// const state = reactive({
//     duration:[],
//     schedule:[],
//     course:[],
//     teacher:[],
// })

onMounted(async() => {
    // const {
    //     duration,
    //     schedule,
    //     course,
    //     teacher
    // } = await getInitialData();
    setInitialData(await getInitialData());
})
const handleTDClick = (beginTime,weekDay) => {
    const scheduleData = data.schedule[`${beginTime}_${weekDay}`]

    // 新增 编辑
    MyMessageBox({
        title: checkHasData(scheduleData),
        btnCancelText: '取消',
        btnConfirmText: '提交',
        type: 'primary',
        insert:h(MyForm,{
            scheduleData,
            weekDay,
            beginTime,
            course:data.course,
            teacher:data.teacher,
            onFormUpdate:setFormData,

            // onFormUpdate(info){
            //     console.log('info----');
            //     console.log(info);
            // }

        }),
        async confirm(){
            console.log('确定')
            if(Object.keys(data.formData).length === 0){
                setFormData({
                   begin_time: beginTime,
                    week_day: weekDay,
                    course: data.course[0].name,
                    teacher: data.teacher[0].name,
                })
            }
            const res = await updateSchedule({data: data.formData});
            setSchedule({...res})
            setFormData({})
            
        },
    })
}
const removeCard = async (data) => {
    const {type} = await removeSchedule(data.id);
    setSchedule({
        type,
        result:data
    })
}
const {
        duration,
        schedule,
        course,
        teacher
    } = toRefs(data)
</script>
<style lang="scss" scoped>

</style>